import datetime
import streamlit as st
import pandas as pd
import plost
from monitoring.plotting import get_index, get_bondyield
from dateutil.relativedelta import relativedelta
import plotly.graph_objects as go
from plotly.subplots import make_subplots

st.set_page_config(layout='wide')

# 市场风格轮动监控：红利、价值、成长；大盘、小盘
freq_mapping = {
    '近一年': 252,
    '近三月': 60,
    '近一月': 20,
    '近一周': 5
}
st.markdown("<h1 style='padding-top: 20px; padding-bottom: 50px; text-align: left; color: #303052'>A股风格轮动</h1>",
            unsafe_allow_html=True)
freq = st.selectbox('选择时间频率', list(freq_mapping.keys()))
freq_value = freq_mapping[freq]

factor_rotation, scalre_rotation = st.columns(2, gap='large')

index_name = {
    '000922.CSI': '中证红利',
    '000300.SH': '沪深300',
    '000906.SH': '中证800',
    '000852.SH': '中证1000',
    '000985.CSI': '中证全指',
    '000058.SH': '全指价值',
    '000057.SH': '全指成长',
    '399373.SZ': '大盘价值',
    '399377.SZ': '小盘价值'
}

with factor_rotation:
    _factor = get_index(['000922.CSI', '000058.SH', '000057.SH'], period=freq_value)
    _factor['index_name'] = _factor['ts_code'].map(index_name)
    factor = _factor.pivot_table(index='trade_date', columns='index_name', values='cum_return').reset_index()
    factor['trade_date'] = pd.to_datetime(factor['trade_date']).dt.strftime('%Y-%m-%d')
    st.markdown(f"<h4 style='text-align: center; color: #A4A7D2 '>{freq}因子风格累计收益率</h3>", unsafe_allow_html=True)
    plost.line_chart(
        data=factor,
        x='trade_date',
        y=['中证红利', '全指成长', '全指价值'],
        height=450
    )
with scalre_rotation:
    _scale = get_index(['399373.SZ', '399377.SZ'], period=freq_value)
    _scale['index_name'] = _scale['ts_code'].map(index_name)
    scale = _scale.pivot_table(index='trade_date', columns='index_name', values='cum_return').reset_index()
    scale['trade_date'] = pd.to_datetime(scale['trade_date']).dt.strftime('%Y-%m-%d')
    st.markdown(f"<h4 style='text-align: center; color: #A4A7D2 '>{freq}因子风格累计收益率</h3>", unsafe_allow_html=True)
    plost.line_chart(
        data=scale,
        x='trade_date',
        y=['大盘价值', '小盘价值'],
        height=450
    )

# 中美国债收益率对比
st.markdown("<h1 style='padding-top: 20px; padding-bottom: 50px; text-align: left; color: #303052'>中美国债收益率对比</h1>",
            unsafe_allow_html=True)
date_col1, date_col2 = st.columns(2, gap='medium')
with date_col1:
    three_years = datetime.datetime.today() - relativedelta(years=3)
    start_date = st.date_input('开始时间', value=three_years)
with date_col2:
    end_date = st.date_input('结束时间', value=datetime.datetime.today())

yield_10, yield_1 = st.columns(2, gap='large')
with yield_10:
    data_10y = get_bondyield(period=10, start_date=start_date, end_date=end_date)
    data_10y['trade_date'] = pd.to_datetime(data_10y['trade_date']).dt.strftime('%Y-%m-%d')
    st.markdown("<h4 style='text-align: center; color: #A4A7D2 '>中美10年国债收益率对比</h3>",
                unsafe_allow_html=True)
    fig = make_subplots(specs=[[{"secondary_y": True}]])
    fig.update_layout(height=450, margin=dict(l=50, r=50, t=10, b=10))
    fig.add_trace(go.Scatter(x=data_10y['trade_date'], y=data_10y['中债10年'], name='中债10年'), secondary_y=False)
    fig.add_trace(go.Scatter(x=data_10y['trade_date'], y=data_10y['美债10年'], name='美债10年'), secondary_y=False)
    fig.add_trace(go.Scatter(x=data_10y['trade_date'], y=data_10y['利差'], name='利差'), secondary_y=True)
    st.plotly_chart(fig, config={'displayModeBar': False}, use_container_width=True,
                    key='bond_10y')

with yield_1:
    data_1y = get_bondyield(period=1, start_date=start_date, end_date=end_date)
    data_1y['trade_date'] = pd.to_datetime(data_1y['trade_date']).dt.strftime('%Y-%m-%d')
    st.markdown("<h4 style='text-align: center; color: #A4A7D2 '>中美1年国债收益率对比</h3>",
                unsafe_allow_html=True)
    fig = make_subplots(specs=[[{"secondary_y": True}]])
    fig.update_layout(height=450, margin=dict(l=50, r=50, t=10, b=10))
    fig.add_trace(go.Scatter(x=data_1y['trade_date'], y=data_1y['中债1年'], name='中债1年'), secondary_y=False)
    fig.add_trace(go.Scatter(x=data_1y['trade_date'], y=data_1y['美债1年'], name='美债1年'), secondary_y=False)
    fig.add_trace(go.Scatter(x=data_1y['trade_date'], y=data_1y['利差'], name='利差'), secondary_y=True)
    st.plotly_chart(fig, config={'displayModeBar': False}, use_container_width=True,
                    key='bond_1y')
